﻿/*
    Project: IV:MP GUI Editor (http://code.google.com/p/ivmp-gui-editor)
    Code license: GNU Lesser GPL (http://www.gnu.org/copyleft/lesser.html) 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IvmpEditor
{
    public class SquirrelCodeStack
    {
        public const string C_COMMENT_LINE = " * ";

        StringBuilder totalString;
        public SquirrelCodeStack() { totalString = new StringBuilder(); }
        public SquirrelCodeStack(string source)
        {
            if ((source != null && source != String.Empty )
                && !source.EndsWith(Environment.NewLine))
                source += Environment.NewLine;
            totalString = new StringBuilder(source);
        }
        public override string ToString() { return totalString.ToString(); }
        public string WritingTableName = null;

        public void wAppend(string str) { totalString.Append(str + ";" + Environment.NewLine); }
        public void wComment(string commentText)
        {
            if (!commentText.Contains(Environment.NewLine))
                totalString.Append("/* " + commentText + " */");
            else
                totalString.Append("/*" + Environment.NewLine + C_COMMENT_LINE+
                    commentText.Replace(Environment.NewLine, Environment.NewLine + C_COMMENT_LINE)
                    + Environment.NewLine + "*/");
            totalString.Append(Environment.NewLine);
        }
        public void wSet(string obj, string memberName, string value, bool newLocal)
        {
            if (obj != null)
                obj += '.';
            var sep = "=";
            if (WritingTableName != null)
            {
                obj = WritingTableName + '.' + obj;
                if (newLocal)
                    sep = "<-";
            }
            wAppend(obj + memberName + ' ' + sep + ' ' + value);
        }
        public void wFunc(string obj, string memberName, string funcName, string arguments)
        {
            if (obj != null)
                obj += '.';
            if (WritingTableName != null)
                obj = WritingTableName + '.' + obj;
            wAppend(obj + memberName + '.' + funcName + '(' + arguments + ')');
        }
        public void wSetTable(string tableName, bool newLocal)
        {
            WritingTableName = tableName;
            if (tableName != null)
            {
                if (newLocal)
                    tableName = "local " + tableName;
                wAppend(tableName + " = {}");
            }
        }
    }
}